Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
Select the last element that is not empty (innerText !== "") of a class with querySelector

I'm try to select the last element that is not empty of a class.

For example, here I would like to select the second element:

<span class="test">A</span>
<span class="test">B</span>
<span class="test"></span>
<span class="test"></span>

But because the innerText changes (with the actions of the user), I can't just use

document.querySelector(".test:nth-of-type(2)");

I've tried this but it doesn't work :

document.querySelector('.test:not(:empty):nth-last-of-type(1)');

function myFunction(){
  document.querySelector('.test:not(:empty):nth-last-of-type(1)').innerText = "test";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span class="test">A</span><br>
<span class="test">B</span><br>
<span class="test"></span><br>
<span class="test"></span><br>

<input type="button" value="change 2nd element" onclick="myFunction()"/>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Why use querySelector for this? I would suggest this:

document
  .querySelectorAll('.test') // all with test class
  .filter(elem => elem.innerText !== '') // only not empty
  .at(-1) // last element

// or, if you need backward browser compatibility:
document
  .querySelectorAll('.test') // all with test class
  .filter(elem => elem.innerText !== '') // only not empty
  .reverse()[0]
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda